<template>
  <div class="login-account">
    <el-form
      label-width="70px"
      :model="account"
      :rules="loginAccountRules"
      ref="elFormRef"
      class="el-form"
    >
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name" clearable></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="account.password" show-password clearable></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElForm, ElMessage } from 'element-plus'
import { loginAccountRules } from '../config/account-config'
import { accountLogin, getUserInfoById, getUserMenusByRoleId } from '@/service/login'
import type { IAccount } from '@/types'
import { localCache } from '@/utils/cache'
import { ACCOUNT, LOGIN_TOKEN, USERINFO } from '@/constant'
import router from '@/router'
import { useUserStore } from '@/store/user'

const elFormRef = ref<InstanceType<typeof ElForm>>()
const account = reactive<IAccount>({
  // name: 'codeerwhy',
  // password: '123456'
  name: localCache.getCache('account')?.name ?? '',
  password: localCache.getCache('account')?.password ?? ''
})
const userStore = useUserStore()

const loginAction = (isRememberPwd: boolean) => {
  elFormRef.value?.validate(async (valid) => {
    if (valid) {
      // 登录获取token
      const tokenRes = await accountLogin(account)
      if (tokenRes) {
        localCache.setCache(LOGIN_TOKEN, 'myToken')
      }
      // 获取用户信息
      const res = await getUserInfoById('1')
      if (res) {
        userStore.changeUserInfo(res)
        localCache.setCache(USERINFO, res)
      }
      router.push('/main')
      if (isRememberPwd) {
        localCache.setCache(ACCOUNT, account)
      } else {
        localCache.removeCache(ACCOUNT)
      }
    } else {
      ElMessage.warning('请输入正确的用户信息')
    }
  })
}

defineExpose({
  loginAction
})
</script>

<style lang="less" scoped>
.el-form {
  padding-top: 10px;
}
</style>
